package redis;

import redis.clients.jedis.Jedis;
import java.util.Random;

public class PhoneCode {

    //模拟验证码流程
    public static void main(String[] args) {
        String phoneNum = "13151071326X";
        verifyCode(phoneNum); //获取验证码
        boolean verifyResult = verify("123456", phoneNum);//填写验证码
        if (verifyResult)
            System.out.println("验证成功！");
        else
            System.out.println("验证失败！请重试。");
    }

    // 1.生成6位数验证码
    public static String randomCode_6() {
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);
            code += rand;
        }
        return code;
    }

    // 2.每个手机每天只能发送三次验证码，验证码有效期2分钟
    public static void verifyCode( String phoneNum ) {
        Jedis jedis = new Jedis("192.168.0.170", 6379); //连接redis

        String countKey = "VerifyCode" + phoneNum + ":count"; //发送次数key
        String codeKey = "VerifyCode" + phoneNum + ":code"; //验证码key

        //判断发送次数
        String sendCount = jedis.get(countKey);
        if (null == sendCount){ //第一次发送
            jedis.setex(countKey, 60*60*24, "1"); //设置过期时间为1天  计数为1
        }else if (Integer.parseInt(sendCount) < 3){
            jedis.incr(countKey); //计数加一
        }else {
            System.out.println("发送次数已达今天上限！");
            jedis.close();//关闭连接
            return;
        }

        //将验证码存入redis
        String verifyCode = randomCode_6();
        System.out.println("您的验证码为："+verifyCode+"。有效期为2分钟。");
        jedis.setex(codeKey, 60*2, verifyCode);

        jedis.close();//关闭连接
    }

    /**
     * 3.校验验证码
     * @param phoneNum 用户手机号
     * @param code 用户输入的验证码
     * @return 校验一致返回true
     */
    public static boolean verify(String code ,String phoneNum) {
        Jedis jedis = new Jedis("192.168.0.170", 6379); //连接redis
        String codeKey = "VerifyCode" + phoneNum + ":code"; //验证码key
        String verifyCode = jedis.get(codeKey);
        jedis.close();//关闭连接
        return code.equals(verifyCode);
    }
}
